package com.virtium.vpm.controller;

import java.util.ArrayList;
import java.util.ListIterator;

import com.virtium.vpm.dao.DAOFactory;
import com.virtium.vpm.dao.TypeDAO;
import com.virtium.vpm.hibernate.model.Type;

public class TypeManager {
	
	private static ArrayList<Type> typeList;
	public static String getTypeNameByID(int id){		
		try{
			ListIterator<Type> lt = getAllTypes().listIterator();
			while(lt.hasNext()){
				Type type= lt.next();
				if(type.getId().equals(id)) return type.getName();
			}
		}catch(Exception ex){}
		return null;
	}
	
	public static ArrayList<Type> getAllTypes(){
		if(typeList != null) return typeList;
		try{
			TypeDAO typeDAO = DAOFactory.getInstance().getTypeDAO();
			typeList = new ArrayList<Type>();
			typeList.addAll(typeDAO.findAll());
			return typeList; 
		}catch(Exception ex){}
		return null;
	}
	
	public String addNewType(Type type){
		try{
			TypeDAO typeDAO = DAOFactory.getInstance().getTypeDAO();
			typeDAO.save(type);
			update();
			return type.getId()+"";
		}catch(Exception ex){}
		return "";
	}
	
	public void delete(Type type){
		try{
			TypeDAO typeDAO = DAOFactory.getInstance().getTypeDAO();
			typeDAO.delete(type);
			update();
		}catch(Exception ex){}
	}
	
	
	private void update(){
		typeList = null;
		getAllTypes();
	}
}
